package com.cameron.vod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.cameron.vod.service.VodService;
import com.cameron.vod.utils.InitVodClient;
import com.cameron.vod.utils.OssConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author Cameron
 */
@Slf4j
@Service
public class VodServiceImpl implements VodService {
    @Override
    public String uploadVideo(MultipartFile file) {
        String videoId = "";
        try {
            String fileName = file.getOriginalFilename();
            String title = UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));
            InputStream inputStream = file.getInputStream();
            UploadStreamRequest request = new UploadStreamRequest(OssConstants.KEY_ID, OssConstants.KEY_SECRET, title, fileName, inputStream);
            //手动设置阿里云存储区域地址
            request.setStorageLocation(OssConstants.ADDRESS);
            //手动设置服务接入点
            request.setApiRegionId(OssConstants.REGION);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            videoId = response.getVideoId();
            if (response.isSuccess()) {
                log.info("VideoId=" + videoId);
            } else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
                log.error("VideoId=" + videoId);
                log.error("ErrorCode=" + response.getCode());
                log.error("ErrorMessage=" + response.getMessage());
            }
        } catch (IOException e) {
            log.error(e.getMessage());
            return null;
        }
        return videoId;
    }

    @Override
    public boolean delVideo(String videoId) {

        DefaultAcsClient client = InitVodClient.initVodClient(OssConstants.KEY_ID, OssConstants.KEY_SECRET);
        try {
            //创建删除视频对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //设置删除视频的id，可删除多个，用逗号隔开
            request.setVideoIds(videoId);
            //调用初始化对象的方法实现删除
            client.getAcsResponse(request);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
